<script setup lang="ts">
import ToolView from "@/modules/tools/layout/tool-view.vue";
import { useStorage } from "@vueuse/core";
import { computedRefreshable } from "@/framework/vue/composable/computed-refreshable.ts";
import { withDefaultOnError } from "@/framework/util/defaults.ts";
import * as uuid from "uuid";
import { copyText } from "@/util/clipboard.ts";

const versions = ["NIL", "v1", "v4", "v6", "v7"] as const;

const version = useStorage<(typeof versions)[number]>("uuid-generator:version", "v4");
const count = useStorage("uuid-generator:count", 1);

const generators = {
  NIL: () => uuid.NIL,
  v1: (index: number) =>
    uuid.v1({
      clockseq: index,
      msecs: Date.now(),
      nsecs: Math.floor(Math.random() * 10000),
      node: new Uint8Array(Array.from({ length: 6 }, () => Math.floor(Math.random() * 256))),
    }),
  v4: () => uuid.v4(),
  v6: () => uuid.v6(),
  v7: () => uuid.v7(),
};

const [uuids, refreshUUIDs] = computedRefreshable(() =>
  withDefaultOnError(() => {
    return Array.from({ length: count.value }, (_, index) => {
      const generator = generators[version.value] ?? generators.NIL;
      return generator(index);
    }).join("\n");
  }, ""),
);
</script>

<template>
  <tool-view
    title="UUID生成器"
    description="通用唯一标识符（UUID）是一个128位数字，用于标识计算机系统中的信息。可能的UUID数量为16^32，即2^128或约3.4x10^38（这是一个很大的数字！）。"
  >
    <div class="pv-20 full-view flex-center">
      <a-form class="w-80p" :label-col="{ span: 5 }">
        <a-form-item label="UUID版本">
          <a-radio-group :options="versions" option-type="button" v-model:value="version" />
        </a-form-item>
        <a-form-item label="生成数量">
          <a-input-number v-model:value="count" :min="1" :max="100" class="w-full" />
        </a-form-item>
        <a-form-item label="结果">
          <a-textarea :value="uuids" readonly :auto-size="{ minRows: 10, maxRows: 10 }" />
        </a-form-item>
        <a-form-item label=" " :colon="false">
          <a-space>
            <a-button @click="refreshUUIDs">刷新</a-button>
            <a-button @click="copyText(uuids)">复制</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
  </tool-view>
</template>

<style scoped lang="less"></style>
